<?php
/**
 * Created by PhpStorm.
 * Author: 芸众商城 www.yunzshop.com
 * Date: 17/2/22
 * Time: 上午11:56
 */

namespace App\Http\Controllers\Api;

use App\Common\Components\ApiController;
use App\Models\HhmVendorVerifiy;
use App\Models\OrderOutbound;
use App\Models\GeneralUser;
use App\Models\HhmMember;
use GuzzleHttp\Promise\Create;
use App\Models\PickupPointVendor;
use Illuminate\Support\Facades\Log;
class UserController extends ApiController
{
    protected $publicController = ['Login'];
    protected $publicAction = ['index', 'phoneSetGet', 'chekAccount', 'loginMode'];
    protected $ignoreAction = ['index', 'phoneSetGet', 'chekAccount', 'loginMode'];
    protected $APPID = 'wxba6d430072eb9640';
    protected $APPSECRET = 'b4e9c3a5f399a946ef1021cf9bc0c16b';



        
        
//     }
    public function getUser()
    {
            $APPID = $this->APPID;
            $APPSECRET = $this->APPSECRET;
            
            // 一、获取用户授权回调里的code  code只有五分钟有效
            // 这个接口是特例，code参数在param对象中
            $code = request()->input('param.code');
            
            // 检查code参数是否存在
            if (empty($code)) {
                return $this->errorJson('缺少微信授权码参数');
            }
     
            // 取出授权结束后的跳转地址
            $path = request()->input('param.state', '');
            
            // 二、通过code获取网页授权access_token 有效期7200s,过期需要重新获取，这里暂不处理过期的问题
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$APPID&secret=$APPSECRET&code=$code&grant_type=authorization_code";
            $token_curl = $this->http_curl($url);
            
            // 检查获取access_token是否成功
            if (!$token_curl || isset($token_curl['errcode'])) {
                return $this->errorJson('获取微信access_token失败: ' . ($token_curl['errmsg'] ?? '未知错误'));
            }

            // 三、获取用户信息
            $url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=".$token_curl['access_token']."&openid=".$token_curl['openid']."&lang=zh_CN";
            $userinfo = $this->http_curl($url2);
            
            // 检查获取用户信息是否成功
            if (!$userinfo || isset($userinfo['errcode'])) {
                return $this->errorJson('获取微信用户信息失败: ' . ($userinfo['errmsg'] ?? '未知错误') . '错误码: ' . ($userinfo['errcode'] ?? '未知错误') . 'url: ' . $url2);
            }
            
            $openid = $token_curl['openid'];
            $data = HhmMember::where('openid', $openid)->first();
            
            if($data){
                // 用户已存在，比对数据并更新有变化的字段
                $updateData = [];
                
                // ✅ 如果微信返回的昵称是"微信用户"，说明用户设置了隐私保护
                // 此时微信返回的所有信息都可能是默认值，不应该更新数据库
                $newNickname = $userinfo['nickname'] ?? '';
                if ($newNickname !== '微信用户') {
                    // 只有昵称不是"微信用户"时，才更新数据
                    
                    // 昵称更新：新昵称不为空且与旧昵称不同
                    if (!empty($newNickname) && $data->nickname !== $newNickname) {
                        $updateData['nickname'] = $newNickname;
                    }
                    
                    // 头像更新：新头像不为空且与旧头像不同
                    $newAvatar = $userinfo['headimgurl'] ?? '';
                    if (!empty($newAvatar) && $data->avatar !== $newAvatar) {
                        $updateData['avatar'] = $newAvatar;
                    }
                    
                    // 性别更新：新性别不为0且与旧性别不同
                    $newGender = $userinfo['sex'] ?? 0;
                    if ($newGender != 0 && $data->gender != $newGender) {
                        $updateData['gender'] = $newGender;
                    }
                    
                    if(!empty($updateData)) {
                        $updateData['updated_at'] = time();
                        $data->update($updateData);
                    }
                }
                
                $id = $data->id;
                $GeneralUser = GeneralUser::where(['third_id' => $id,'code' => 'HHM'])->first();
                if($GeneralUser) {
                    $data['uid'] = $GeneralUser->member_id; // 使用id字段而不是member_id
                }
            } else {
                // 用户不存在，新增数据
                $data = HhmMember::insertData($userinfo, 1);
            }
            
            return $this->successJson('获取用户信息成功', $data);

    }

    


    public function updateLastLoginTime($uid)
    {
        // event(new MemberLoginEvent($uid));
        // MemberShopInfo::where('member_id', $uid)->update(['last_login_time' => time()]);
    }

    public function phoneSetGet()
    {
        // $phone_oauth = \Setting::get('shop_app.pay.phone_oauth');

        // if (empty($phone_oauth)) {
        //     $phone_oauth = '0';
        // }
        // return $this->successJson('ok', ['phone_oauth' => $phone_oauth]);
    }

    public function checkAccount()
    {
        // $type = \YunShop::request()->type;

        // if (1 == $type) {
        //     $member = MemberFactory::create($type);
        //     $member->chekAccount();
        // }
    }

    public function checkLogin()
    {
        return $this->successJson('已登录');
    }

    /**
     * 发送短信验证码
     */
    public function sendSms()
    {
        $mobile = request()->input('param.mobile');
        
        if (empty($mobile)) {
            return $this->errorJson('手机号不能为空');
        }
        
        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            return $this->errorJson('手机号格式不正确');
        }
        
        // 检查手机号是否已被绑定
        $existMember = HhmMember::where('mobile', $mobile)->first();
        if ($existMember) {
            return $this->errorJson('该手机号已被绑定，无法重复绑定');
        }
        
        $url = 'https://yidui.jiujiefang7979.cn/addons/yun_shop/api.php?i=1&scope=pass&route=message.ali-sms.sendSms';
        $data = array(
            'mobile' => $mobile,
        );
        
        $res = self::json_post($url, $data);
        $res = json_decode($res);
        
        if ($res && $res->result == 1) {
            return $this->successJson('验证码发送成功');
        } else {
            return $this->errorJson($res->msg ?? '验证码发送失败');
        }
    }

    /**
     * 验证短信验证码
     */
    public function validateCode()
    {
        $mobile = request()->input('param.mobile');
        $code = request()->input('param.code');
        
        if (empty($mobile)) {
            return $this->errorJson('手机号不能为空');
        }
        
        if (empty($code)) {
            return $this->errorJson('验证码不能为空');
        }
        
        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            return $this->errorJson('手机号格式不正确');
        }
        
        $url = 'https://yidui.jiujiefang7979.cn/addons/yun_shop/api.php?i=1&scope=pass&route=message.ali-sms.validateCode';
        $data = array(
            'mobile' => $mobile,
            'code' => $code,
        );
        
        $res = self::json_post($url, $data);
        $res = json_decode($res);
        
        if ($res && $res->result == 1) {
            return $this->successJson('验证码验证成功', $res->data ?? []);
        } else {
            return $this->errorJson($res->msg ?? '验证码验证失败');
        }
    }

    /**
     * 查询手机号是否已绑定
     */
    public function checkMobileExists()
    {
        $mobile = request()->input('param.mobile');

        if (empty($mobile)) {
            return $this->errorJson('手机号不能为空');
        }

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            return $this->errorJson('手机号格式不正确');
        }

        $member = HhmMember::where('mobile', $mobile)->first();

        if ($member) {
            return $this->successJson('手机号已绑定', [
                'exists' => true,
                'member' => [
                    'id' => $member->id,
                    'nickname' => $member->nickname,
                    'avatar' => $member->avatar,
                    'openid' => $member->openid,
                    'mobile' => $member->mobile,
                ],
            ]);
        }

        return $this->successJson('手机号未绑定', [
            'exists' => false,
        ]);
    }

    /**
     * 用户登录接口
     */
    public function login()
    {
        $mobile = request()->input('param.mobile');
        $openid = request()->input('param.openid');
        $code = request()->input('param.code');
        $force = request()->input('param.force', 0);
        $force = (int)$force === 1;

        if (empty($mobile)) {
            Log::warning('[UserController@login] 登录失败：缺少手机号');
            return response()->json([
                'result' => 0,
                'msg' => '手机号不能为空',
                'data' => null,
            ]);
        }
        
        if (empty($openid)) {
            Log::warning('[UserController@login] 登录失败：缺少 openid', [
                'mobile' => $mobile,
            ]);
            return response()->json([
                'result' => 0,
                'msg' => 'openid不能为空',
                'data' => null,
            ]);
        }
        
        if (empty($code)) {
            Log::warning('[UserController@login] 登录失败：缺少验证码', [
                'mobile' => $mobile,
                'openid' => $openid,
            ]);
            return response()->json([
                'result' => 0,
                'msg' => '验证码不能为空',
                'data' => null,
            ]);
        }
        
        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            Log::warning('[UserController@login] 登录失败：手机号格式错误', [
                'mobile' => $mobile,
            ]);
            return response()->json([
                'result' => 0,
                'msg' => '手机号格式不正确',
                'data' => null,
            ]);
        }
        
        // 1. 检查手机号是否已被绑定
        $existMember = HhmMember::where('mobile', $mobile)->first();

        // 2. 先验证验证码
        $validateUrl = 'https://yidui.jiujiefang7979.cn/addons/yun_shop/api.php?i=1&scope=pass&route=message.ali-sms.validateCode';
        $validateData = array(
            'mobile' => $mobile,
            'code' => $code,
        );
        
        $validateRes = self::json_post($validateUrl, $validateData);
        $validateRes = json_decode($validateRes);
        
        if (!$validateRes || $validateRes->result != 1) {
            Log::error('[UserController@login] 验证码验证失败', [
                'mobile' => $mobile,
                'openid' => $openid,
                'validate_response' => $validateRes,
            ]);
            return response()->json([
                'result' => 0,
                'msg' => $validateRes->msg ?? '验证码验证失败',
                'data' => $validateRes->data ?? null,
            ]);
        }
        
        // 3. 用openid查询ims_hhm_member
        $member = HhmMember::where('openid', $openid)->first();
        
        if (!$member) {
            Log::warning('[UserController@login] 登录失败：绑定 openid 的用户不存在', [
                'mobile' => $mobile,
                'openid' => $openid,
            ]);
            return response()->json([
                'result' => 0,
                'msg' => '用户不存在，请先进行微信授权',
                'data' => null,
            ]);
        }
        
        if ($existMember && $existMember->id !== $member->id) {
            if (!$force) {
                return response()->json([
                    'result' => 0,
                    'msg' => '该手机号已被绑定',
                    'data' => [
                        'nickname' => $existMember->nickname,
                        'member_id' => $existMember->id,
                    ],
                ]);
            }

            $existMember->update([
                'mobile' => null,
                'updated_at' => time()
            ]);
        }

        // 4. 如果用户没有手机号或需要更新手机号，更新手机号
        if (empty($member->mobile) || $member->mobile !== $mobile) {
            $member->update([
                'mobile' => $mobile,
                'updated_at' => time()
            ]);
        }
        
        // 4. 调用登录接口
        $loginUrl = 'https://yidui.jiujiefang7979.cn/addons/yun_shop/api.php?i=1&scope=pass&route=member.user.index';
        $loginData = array(
            'mobile' => $mobile,
            'code' => 'HHM',
            'open_id' => $openid,
            'userinfo' => $member->toArray(),
            'third_id' => $member->id
        );
        
        $loginRes = self::json_post($loginUrl, $loginData);
        $loginRes = json_decode($loginRes);
        
        if ($loginRes && $loginRes->result == 1) {
            $successdata['uid'] =$loginRes->data;
            return response()->json([
                'result' => 1,
                'msg' => '登录成功',
                'data' => $successdata ?? null,
            ]);
        } else {
            Log::error('[UserController@login] 登录失败：远程接口返回错误', [
                'member_id' => $member->id,
                'mobile' => $mobile,
                'response' => $loginRes,
            ]);
            return response()->json([
                'result' => 0,
                'msg' => $loginRes->msg ?? '登录失败',
                'data' => $loginRes->data ?? null,
            ]);
        }
    }

    /**
     * 核销
     */
    public function verifiy(){
        $outbound_id = request()->input('param.outbound_id');
        $user_id = request()->input('uid');
        $store_id = request()->input('param.store_id');
        $OrderOutbound = OrderOutbound::where('id',$outbound_id)->first();
        if($OrderOutbound->status!=1){
            return $this->errorJson('订单无需核销');
        }
        $vendor_id =$OrderOutbound->vendor_id;
        $vendor_ids = PickupPointVendor::getVendorIdsByStore($store_id);
        if(!in_array($vendor_id,$vendor_ids)){
            return $this->errorJson('门店无权限核销');
        }
        $url = 'https://yidui.jiujiefang7979.cn/addons/yun_shop/api.php?i=1&scope=pass&route=order.out-bound.receive';
        $data = array(
            'id' => $outbound_id,
            'scope' => 'pass',
            'deliver_id' => $store_id,
        ); 
        $res = self::json_post($url,$data);
        $res=json_decode($res);
        $result = $res->result;
        if($result==1){
            HhmVendorVerifiy::create([
                'outbound_id' => $outbound_id,
                'user_id' => $user_id,
                'vendor_id' => $vendor_id,
                'store_id' => $store_id,
            ]);
            return $this->successJson('成功');
        }else{
            return $this->errorJson($res->msg);
        }
    }

    /**
     * HTTP GET 请求
     * @param string $url 请求URL
     * @return array|false 返回JSON解析后的数组或false
     */
    private function http_curl($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        
        if ($errorno) {
            curl_close($curl);
            return false;
        }
        
        curl_close($curl);
        
        // 解析JSON响应
        $result = json_decode($res, true);
        return $result !== null ? $result : false;
    }

    //http 请求
    function json_post($url, $data = NULL){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length:' . strlen($data),
                'Cache-Control: no-cache',
                'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;
    }
}
